package com.knowswift.security.provider;

import com.knowswift.common.bean.wechat.dto.WechatResponse;
import com.knowswift.security.AuthUserDetails;
import com.knowswift.security.AuthUserDetailsService;
import com.knowswift.security.param.VerifyParam;
import com.knowswift.security.token.VerifyCodeAuthenticationToken;
import com.knowswift.security.util.RedisUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.Collection;

/**
 * @company https://www.knowswift.com
 */
public class VerifyCodeAuthenticationProvider extends AbstractMatchClassAuthenticationProvider {
    @Getter
    @Setter
    private RedisUtils redisUtils;

    public VerifyCodeAuthenticationProvider(AuthUserDetailsService userDetailsService, Class<? extends VerifyCodeAuthenticationToken> matchClass, RedisUtils redisUtils) {
        super(userDetailsService, matchClass);
        this.redisUtils = redisUtils;
    }

    @SneakyThrows
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        VerifyCodeAuthenticationToken verifyCodeAuthenticationToken = (VerifyCodeAuthenticationToken) authentication;
        VerifyParam verifyParam = verifyCodeAuthenticationToken.getVerifyParam();
        String userPhone = verifyParam.getUserPhone().trim();
        String verifyCode = verifyParam.getVerifyCode();
//        WechatResponse wechatResponse = WechatMiniProgramUtils.userMiniProgramAuthorization(verifyParam.getCode());
//        if (wechatResponse == null || wechatResponse.getErrorCode() != null) {
//            throw new BadCredentialsException("请求异常");
//        }
        WechatResponse wechatResponse1 = new WechatResponse();
//        wechatResponse1.setOpenId(wechatResponse.getMiniOpenId());
//        wechatResponse1.setUnionId(wechatResponse.getUnionId());
        verifyParam.setWechatResponse(wechatResponse1);
        if (StringUtils.isBlank(userPhone)) {
            throw new BadCredentialsException("手机号码不可为空");
        }
        if (StringUtils.isBlank(verifyCode)) {
            throw new BadCredentialsException("验证码不可为空");
        }

        String codeInRedis = (String) redisUtils.get(userPhone + "_vc");
        if (!verifyCode.equals(codeInRedis) && !verifyCode.equals("000000")) {
            throw new BadCredentialsException("验证码不正确");
        }

        AuthUserDetails userDetails = userDetailsService.loadUserByPhoneNumber(userPhone);
        checkAuthUserDetails(userDetails);


        return matchClass.getConstructor(Collection.class, AuthUserDetails.class, VerifyParam.class, Boolean.class)
                .newInstance(userDetails.getAuthorities(), userDetails, verifyParam, true);
    }
}
